from pyraf import iraf
from scipy import signal
import pyfits
import numpy as np
import os

#write star.coo!!!!!!!!
band = 'R'
filepath="/Users/xiaojia/xinglong/v463/20151212/"
x1 = 586
y1 = 635

coorefFile = open(filepath+'star'+band+'.coo')
coolines = coorefFile.readlines()
listname = open(filepath+band+"image.lst",'r')
lines = listname.readlines()
file1 = pyfits.open(lines[0].strip())
image1 = file1[0].data
coolistfile = open(filepath+band+'Coo.lst','w')
for line in lines :
    line = line.strip()
    file2 = pyfits.open(line)
    image2 = file2[0].data
    data1 = image1[y1:y1+120,x1:x1+120]
    data2 = image2[y1-40:y1+160,x1-40:x1+160]
    c = signal.correlate(data2,data1,'valid')
    #print c
    #print np.shape(c)
    #print np.where(c == c.max())
    index_min = np.where(c == c.max())
    shiftx = 40 - index_min[1]
    shifty = 40 - index_min[0]
    cooname = line + '.photcoo'
    coofile = open(cooname,'w')
    for cooline in coolines :
        cooline = cooline.strip().split()
        coorefx = int(cooline[0])
        coorefy = int(cooline[1])
        coofile.write(str(coorefx-shiftx[0])+' '+str(coorefy-shifty[0])+'\n')
    coofile.close()
    coolistfile.write(cooname+'\n')
coolistfile.close()

#iraf.phot('@R.lst','@Rcoo.lst')
